package com.hfy.music.service.impl;

import com.hfy.model.vo.MusicVo;
import com.hfy.music.mapper.DetailMusicMapper;
import com.hfy.music.service.DetailMusicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import result.Result;

import static constants.RedisConstants.MUSIC_COMMENT_KEY;
import static constants.RedisConstants.MUSIC_LIKE_KEY;

/**
 * @ author 韩
 * time: 2024/6/7 17:09
 */
@Service
public class DetailMusicServiceImpl implements DetailMusicService {

    @Autowired
    private DetailMusicMapper detailMusicMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public Result queryMusicDetail(Integer musicId, Long account) {
        if (musicId == null || account == null) return Result.error("参数不能为空");

        MusicVo vo = detailMusicMapper.queryMusicDetail(musicId);
        Integer rows = detailMusicMapper.queryMusicLikeByAccount(0, musicId,account);
        boolean isLike = rows != null && rows > 0;
        vo.setIsLike(isLike);
        // 再查询评论数和点赞数
        // 去redis里进行查询
        String likeCount = redisTemplate.opsForValue().get(MUSIC_LIKE_KEY + musicId);
        String commentCount = redisTemplate.opsForValue().get(MUSIC_COMMENT_KEY + musicId);
        if (likeCount == null) {
            // 如果在redis中无法取到数据 就直接访问数据库获取计数数据，并同步到redis
            Integer like = detailMusicMapper.queryLikeCount(0,musicId);
            // 需要默认给它置为0
            if(like == null) like = 0;
            Integer unlike = detailMusicMapper.queryUnlikeCount(0,musicId);
            if(unlike == null) unlike = 0;

            likeCount = String.valueOf(like - unlike);
            // 同步到redis
            redisTemplate.opsForValue().set(MUSIC_LIKE_KEY + musicId,likeCount);

        }
        if (commentCount == null) {
            // 如果在redis中无法取到数据 就直接访问数据库获取计数数据，并同步到redis
            Integer comment = detailMusicMapper.queryCommentCount(0,musicId);
            if(comment == null) comment = 0;

            Integer uncomment = detailMusicMapper.queryUncommentCount(0,musicId);
            if(uncomment == null) uncomment = 0;

            commentCount = String.valueOf(comment - uncomment);
            // 同步到redis
            redisTemplate.opsForValue().set(MUSIC_COMMENT_KEY + musicId, commentCount);
        }
        if (Integer.parseInt(likeCount) < 0 || Integer.parseInt(commentCount) < 0) {
            return Result.error("出现问题，点赞或评论数为负数");
        }
        vo.setLikeCount(Integer.valueOf(likeCount));
        vo.setCommentCount(Integer.valueOf(commentCount));

        return Result.ok(vo);
    }
}
